from django.shortcuts import render,redirect
# 导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
# 导入类视图
from django.views import View


import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from django_test.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from django_test.settings import BASE_DIR

# 导包
from django.db.models import Q,F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# 导入表
from myapp.models import User, Goods, Cart, Comment
# 导入序列化对象
from myapp.myser import UserSer, GoodsSer, CartSer, CommentSer

# 导包
import redis

# 图像处理
import cv2

# 定义地址和端口
host = '127.0.0.1'
port = 6379

# 建立redis连接
r = redis.Redis(host=host,port=port)

# 导入pymongo
import pymongo

# 建立mongo的链接对象
mongo_client = pymongo.MongoClient(host='localhost', port=27017)

# 商品评论获取
class CommentList(APIView):

    def get(self, request):

        gid = request.GET.get("gid", None)

        # 查询数据
        comments = Comment.objects.filter(gid=gid).order_by("-id")

        # 序列化
        comments_ser = CommentSer(comments, many=True)

        return Response(comments_ser.data)

# 商品评论
class CommentInsert(APIView):
    def post(self, request):

        # 获取客户端ip
        if 'HTTP_X_FORWARDED_FOR' in request.META:

            ip = request.META.get('HTTP_X_FORWARDED_FOR')

        else:

            ip = request.META.get('REMOTE_ADDR')

        # if r.get(ip):

        try:
            if r.llen(ip) > 3:

                return Response({'code': 403, 'message': '您评论的过快，请歇一歇'})

        except Exception as e:
            pass

        # 初始化参数
        comment = CommentSer(data=request.data)

        # 验证字段
        if comment.is_valid():

            # 进行入库
            comment.save()

            # 设置评论间隔时间
            # r.set(ip,"123")

            r.lpush(ip, 1)
            r.expire(ip, 30)

        return Response({'code': 200, 'message': '评论成功'})

# 商品信息接口
class GoodInfo(APIView):
    def get(self, request):
        id = request.GET.get('id', None)

        # 查询数据
        good = Goods.objects.get(id=id)

        # 序列化操作
        good_ser = GoodsSer(good)

        return Response(good_ser.data)

# 商品列表页
class GoodsList(APIView):
    def get(self, request):
        # 查询数据
        goodslist = Goods.objects.all()

        # 查询总数量
        count = Goods.objects.count()

        # 序列化操作
        goods_ser = GoodsSer(goodslist, many=True)

        res = {}
        res['code'] = count
        res['data'] = goods_ser.data
        return Response(res)

# 登录接口
class Login(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 查询数据
        user = User.objects.filter(username=username, password=make_password(password)).first()

        if user:
            return Response({'code': 200, 'message': '登陆成功'})
        
        else:
            return Response({'code': 403, 'message': '用户名或密码错误'})

# MD5加密
def make_password(mypass):
    # 生成MD5对象
    md5 = hashlib.md5()
    # 转码操作
    mypass_utf8 = str(mypass).encode(encoding='utf-8')
    # 加密操作
    md5.update(mypass_utf8)
    # 返回密文
    return md5.hexdigest()

# 注册接口
class Register(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 查询数据
        user = User.objects.filter(username=username).first()

        # 排重
        if user:
            return Response({'code': 403, 'message': '该用户名已存在'})

        # 入库
        user = User(username=username, password=make_password(password)).save()

        return Response({'code': 200, 'message': '注册成功'})


